<?php
/**
 * 管理后台登录授权中间键
 * Date: 2025/08/31
 */

namespace App\Http\Middleware;

use App\Http\Traits\ApiResponse;
use App\Services\Admin\AuthService;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminAuthenticate
{
    use ApiResponse;

    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function handle($request, Closure $next)
    {
        // 授权登录校验
        if (!Auth::guard('admin')->check()) {
            return $this->failed('登录授权失败', 401);
        }

        try {
            // 管理员登录授权检测
            $adminInfo = (new AuthService())->loginCheck(['id' => Auth::guard('admin')->id()]);
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage(), $exception->getCode());
        }

        $request->adminInfo = $adminInfo->toArray();
        return $next($request);
    }
}
